package com.heyi.nettylong.common;

import com.heyi.nettylong.common.protobuf.Message;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 存放同步消息的订阅者
 * @author dengfeng
 * @date 2022/12/613:45
 */
@Slf4j
public class MessageRepository {

    private static Map<Integer,MessageListener> concurrentHashMap=new ConcurrentHashMap<Integer,MessageListener>();

    static AtomicInteger atomicInteger = new AtomicInteger(1);

    public static void put(Message.MessageBase msgB){
        if(concurrentHashMap.containsKey(msgB.getMsgId())){
            concurrentHashMap.get(msgB.getMsgId()).receiveMessage(msgB.getData());
            concurrentHashMap.remove(msgB.getMsgId());
        }else{
            log.error("返回同步消息找不到Listener:{}--{}--{}", msgB.getClientId(), msgB.getMsgId() ,msgB.getData());
        }
    }

    public static int buildSequence(){
        return atomicInteger.getAndIncrement();
    }

    public static void addListener(Integer msgId, MessageListener ml){
        concurrentHashMap.put(msgId, ml);
    }

    public static void removeListener(Integer msgId){
        concurrentHashMap.remove(msgId);
    }
}
